<?php
namespace Home\Controller\API;
use Think\Controller;
/*
 * 用户控制器 2016.5.27
 * author:candy
 */
class UserController extends Controller {
    
    public function _empty($name){
        $this->display("Event:404");      
    }


    public function index(){
        $this->basicinfo();
    }

    /**
     * 1.登入
     * @return [type] [description]
     */
    public function login(){
        if(!IS_POST){
            $this->ajaxReturn(array('status'=>'error'));
        }else{
            $User = M('User');
            $User->account = I('post.username');
            $User->password = I('post.password');
            $result = $User->where('account="'.$User->account.'"')->find();
            if($result&&$result['password'] == $User->password){
                $userinfo = $result;
                if ($result['type']=='storekeeper') {
                    $shop = M('shop');
                    $shop_id = $shop->where('user_id',$result['user_id'])->field('shop_id')->find();
                    //如果是店家添加商铺id到session
                    session('shop_id',$shop_id);
                }
                $this->ajaxReturn(array('status'=>'ok','uid'=>$result['user_id']));
                session('user',$userinfo);
            }else{
                $this->ajaxReturn(array('status'=>'error'));
            }
        }
    }
    /**
     2.短信还没做
     */

    /**
     * 3.注册
     * 
     */
    public function basicinfo(){
        $sessionUser = session('user');
        $User = M('User');
        if(!isset($sessionUser['user_id'])){
            $this->redirect("User:login");
        }else{
            if(!IS_POST){
                $userinfo = $User->where('user_id='.$sessionUser['user_id'])->find();
                if($userinfo){
                    $this->assign('user',$userinfo);
                    $this->display("User:index");
                }
            }else{
                $User->phone = I('post.phone');
                $User->email = I('post.email');
                $User->name = I('post.name');
                $sessionUser['name'] = $User->name;
                if($_FILES['photo']['size'][0]>0)
                    $this->submit();
                if($User->where('user_id='.$sessionUser['user_id'])->save()){
                    //更新session用户信息
                    session('user',$sessionUser);
                    $this->success('修改成功');
                }else{
                    if((I('post.phone')==session('user.phone'))
                        &&(I('post.email')==session('user.email'))
                        &&(I('post.name')==session('user.name'))){
                        $this->success('修改成功');
                    }
                    else{
                        $this->error('没有做任何修改');
                    }
                }

            }
        }
    }


    /**
     * 6.6
     * 修改用户信息
     */
    public function saveUser(){
        $User = M('User');
        $User->create();
        return $User->save();
    }

    /**
     * 6.14
     * api
     * 修改密码(根据用户名)
     */
    public function editPwd(){
        $userinfo = session('user');
        if(!IS_POST){
             $this->ajaxReturn(array('status'=>'error'));
        }else{
            $User = M('User');
            $username = I('post.username');
            $oldpwd = I('post.oripassword');
            $result = $User->where('account="'.$username.'"')->find();
            if($result&&$result['password'] == $oldpwd){
                $newpwd = I('post.newpassword');
                $User->password = $newpwd;
                if($User->where('account="'.$username.'"')->save()){
                    //更新session用户信息
                    $userinfo['password'] = $newpwd;
                    session('user',$userinfo);
                    $this->ajaxReturn(array('status'=>'ok'));
                }else{
                    $this->ajaxReturn(array('status'=>'error'));
                }
            }else{
                $this->ajaxReturn(array('status'=>'error'));
            }
        }
    }

    /**
     * 6.11
     * 修改头像
     */
    public function editpic(){

    }

    /**
     * 6.6
     * 检查密码是否对
     */
    public function checkPassword($password=NULL){
        $userinfo = session('user');
        if($password == $userinfo['password']){
            session('allow',true);
            echo 1;
        }else{
            session('allow',false);
            echo 0;
        }
    }
    /**
     * 6.6
     * 注销用户信息
     */
    public function deleteUser(){
        
    }


    /*
     *5.27 上传图像 （大小限制：3M；jpg/gif/png/jpeg）
     *     生成缩略图
     *     修改当前用户的头像
     **/
    public function submit(){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Uploads/user/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件 
        $info = $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功
            /**
             * 上传新的头像，先删除已有头像
             */
            unlink($upload->rootPath.session('user.pic_path').'200x200/'.session('user.pic_name'));
            $cropInfo = $_POST['cropinfo'];
            $image = new \Think\Image(); 
            $pic_list = array();
            $User = M('User');
            foreach ($info as $key => $img) {
                // var_dump($img);
                $image->open($upload->rootPath.$img['savepath'].$img['savename']);
                // 生成一个居中裁剪为200*200的缩略图并保存为thumb.jpg
                $crop = json_decode($cropInfo[$key],true);
                $DIR = $upload->rootPath.$img['savepath'].'200x200/';
                $image->crop($crop['width'],$crop['height'],$crop['x'],$crop['y'])->save($upload->rootPath.$img['savepath'].$img['savename']);
                if (!is_dir($DIR)) mkdir($DIR,0777);
                $image->thumb(200, 200,\Think\Image::IMAGE_THUMB_CENTER)->save($DIR.$img['savename']);
                //删除图片 未做异常处理
                $User->pic_name = $img['savename'];
                $User->pic_path = $img['savepath'];
                $User->where('user_id='.session('user.user_id'))->save();
                session('user.pic_path',$img['savepath']);
                session('user.pic_name',$img['savename']);
                unlink($upload->rootPath.$img['savepath'].$img['savename']);
                $pic_list[] = array('pic_name'=>$img['savename'],'pic_path'=>$img['savepath'],'type'=>'user','id'=>$user_id);
            }
            //批量保存图片 6.6
            $pic = M('Picture');
            $pic->addAll($pic_list);
        }
    }

}